<?php declare(strict_types=1);

namespace Distributed\Event;

use Distributed\Contract\IEvent;
use Communication\TxSocketData;
use UntilDistributed\Log;
use Distributed\Group\TransGroupManage;
use Distributed\Constant;

/**
 * 预提交结果表达
 * @author mg
 *
 */
class ResultPreCommit extends AbstractEvent implements IEvent
{
	/**
	 * {@inheritDoc}
	 * @see \Distributed\Contract\IEvent::parseEvent()
	 */
	public function parseEvent(int $fd): ?TxSocketData
	{
		
		$groupId = $this->data->transGroup->groupId;
		
		
		$socketData = & $this->data;
		
		Log::getInstance()->info('txmanage:  actor response  precommit start, result:' . $socketData->result);
		
		$groupStatus = TransGroupManage::getInstance()->getGroupStatus($groupId);
		
		
		
		if($socketData->result == Constant::$tx_complete_fail ){
			if($groupStatus == Constant::$tx_status_cancommit){
				//设置事务组状态为rollback
				TransGroupManage::getInstance()->updateGroupStatus($groupId, Constant::$tx_status_rollback);
				TransGroupManage::getInstance()->updateItemStatus($groupId, $socketData->transaction, Constant::$tx_status_precommit_fail);
				
				//给发起者发送失败消息
				$starter = TransGroupManage::getInstance()->getTransGroupStarter($groupId);
			}
			
			$response= TxSocketData::createResponse(Constant::$tx_complete_fail);
		}else{
			
			TransGroupManage::getInstance()->updateItemStatus($groupId, $socketData->transaction, Constant::$tx_status_precommit);
			$count = TransGroupManage::getInstance()->statusCount($groupId,'precommit');
			
			//给发起者发送成功消息
			$starter = TransGroupManage::getInstance()->getTransGroupStarter($groupId);
			
			dump($starter);
			if($count == 0){
				TransGroupManage::getInstance()->updateGroupStatus($groupId, Constant::$tx_status_precommit);
				//恢复成功
				$response = TxSocketData::createResponse(Constant::$tx_complete_ok);
				
				
				
			} else {
				$response= TxSocketData::createResponse(Constant::$tx_complete_ok);
			}
		}
		
		
		return $response;
	}
}
